package my.sample.threads;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadName {

	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ThreadName.class);

	public static void main(String[] args) {

		logger.debug("thread testing started");

		long serviceStart = System.currentTimeMillis();
		// ExecutorService discoverExeService = null;
		ThreadPoolExecutor threadPoolExecutor = null;

		try {
			// discoverExeService = Executors.newFixedThreadPool(10);
			threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);

			List<Future<Integer>> futureList = new ArrayList<Future<Integer>>();
			for (int i = 11000; i < 11020; i++) {
				TestThread threadObj = new TestThread(i);
//				futureList.add(threadPoolExecutor.submit(threadObj));
				threadPoolExecutor.submit(threadObj);
			}

/*			for (Future<Integer> future : futureList) {
				future.get();
			}*/

			 boolean check = true;
			 long timeoutMillis = 15 * 1000;
			
			 
			 long startTime  = System.currentTimeMillis();

			  while ( check ) {

//				 logger.debug("active count : " + threadPoolExecutor.getActiveCount()) ;
				 logger.debug("completed task count : " + threadPoolExecutor.getCompletedTaskCount()) ;
				 logger.debug("task count : " + threadPoolExecutor.getTaskCount()) ;
//				 logger.debug("core pool size : " + threadPoolExecutor.getCorePoolSize());
//				 logger.debug("pool size : " + threadPoolExecutor.getPoolSize());
				 
				 long duration = System.currentTimeMillis() - startTime; 
				 
				 if ( threadPoolExecutor.getTaskCount() == threadPoolExecutor.getCompletedTaskCount() || duration > timeoutMillis ) 
					 check = false;
//				 if ( threadPoolExecutor.getTaskCount() == threadPoolExecutor.getCompletedTaskCount() )
			  
				 Thread.sleep(1000);
			  }
			 

		} catch (Exception e) {
			logger.error("Future list exception in DiscoverJob : ", e);
		}

		long serviceStop = System.currentTimeMillis();

		threadPoolExecutor.shutdown();

		logger.info("service completed  in " + ((serviceStop - serviceStart) / 1000) + " seconds");

	}
}
